home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / io.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  62KB  |  1,977 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. The io module provides the Python interfaces to stream handling. The
  6. builtin open function is defined in this module.
  7.  
  8. At the top of the I/O hierarchy is the abstract base class IOBase. It
  9. defines the basic interface to a stream. Note, however, that there is no
  10. separation between reading and writing to streams; implementations are
  11. allowed to throw an IOError if they do not support a given operation.
  12.  
  13. Extending IOBase is RawIOBase which deals simply with the reading and
  14. writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
  15. an interface to OS files.
  16.  
  17. BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
  18. subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
  19. streams that are readable, writable, and both respectively.
  20. BufferedRandom provides a buffered interface to random access
  21. streams. BytesIO is a simple stream of in-memory bytes.
  22.  
  23. Another IOBase subclass, TextIOBase, deals with the encoding and decoding
  24. of streams into text. TextIOWrapper, which extends it, is a buffered text
  25. interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
  26. is a in-memory stream for text.
  27.  
  28. Argument names are not part of the specification, and only the arguments
  29. of open() are intended to be used as keyword arguments.
  30.  
  31. data:
  32.  
  33. DEFAULT_BUFFER_SIZE
  34.  
  35.    An int containing the default buffer size used by the module's buffered
  36.    I/O classes. open() uses the file's blksize (as obtained by os.stat) if
  37.    possible.
  38. """
  39. from __future__ import print_function
  40. from __future__ import unicode_literals
  41. __author__ = 'Guido van Rossum <guido@python.org>, Mike Verdone <mike.verdone@gmail.com>, Mark Russell <mark.russell@zen.co.uk>'
  42. __all__ = [
  43.     'BlockingIOError',
  44.     'open',
  45.     'IOBase',
  46.     'RawIOBase',
  47.     'FileIO',
  48.     'BytesIO',
  49.     'StringIO',
  50.     'BufferedIOBase',
  51.     'BufferedReader',
  52.     'BufferedWriter',
  53.     'BufferedRWPair',
  54.     'BufferedRandom',
  55.     'TextIOBase',
  56.     'TextIOWrapper']
  57. import os
  58. import abc
  59. import codecs
  60. import _fileio
  61. import threading
  62. DEFAULT_BUFFER_SIZE = 8 * 1024
  63. __metaclass__ = type
  64.  
  65. class BlockingIOError(IOError):
  66.     '''Exception raised when I/O would block on a non-blocking I/O stream.'''
  67.     
  68.     def __init__(self, errno, strerror, characters_written = 0):
  69.         IOError.__init__(self, errno, strerror)
  70.         self.characters_written = characters_written
  71.  
  72.  
  73.  
  74. def open(file, mode = 'r', buffering = None, encoding = None, errors = None, newline = None, closefd = True):
  75.     """Open file and return a stream. If the file cannot be opened, an IOError is
  76.     raised.
  77.  
  78.     file is either a string giving the name (and the path if the file
  79.     isn't in the current working directory) of the file to be opened or an
  80.     integer file descriptor of the file to be wrapped. (If a file
  81.     descriptor is given, it is closed when the returned I/O object is
  82.     closed, unless closefd is set to False.)
  83.  
  84.     mode is an optional string that specifies the mode in which the file
  85.     is opened. It defaults to 'r' which means open for reading in text
  86.     mode.  Other common values are 'w' for writing (truncating the file if
  87.     it already exists), and 'a' for appending (which on some Unix systems,
  88.     means that all writes append to the end of the file regardless of the
  89.     current seek position). In text mode, if encoding is not specified the
  90.     encoding used is platform dependent. (For reading and writing raw
  91.     bytes use binary mode and leave encoding unspecified.) The available
  92.     modes are:
  93.  
  94.     ========= ===============================================================
  95.     Character Meaning
  96.     --------- ---------------------------------------------------------------
  97.     'r'       open for reading (default)
  98.     'w'       open for writing, truncating the file first
  99.     'a'       open for writing, appending to the end of the file if it exists
  100.     'b'       binary mode
  101.     't'       text mode (default)
  102.     '+'       open a disk file for updating (reading and writing)
  103.     'U'       universal newline mode (for backwards compatibility; unneeded
  104.               for new code)
  105.     ========= ===============================================================
  106.  
  107.     The default mode is 'rt' (open for reading text). For binary random
  108.     access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  109.     'r+b' opens the file without truncation.
  110.  
  111.     Python distinguishes between files opened in binary and text modes,
  112.     even when the underlying operating system doesn't. Files opened in
  113.     binary mode (appending 'b' to the mode argument) return contents as
  114.     bytes objects without any decoding. In text mode (the default, or when
  115.     't' is appended to the mode argument), the contents of the file are
  116.     returned as strings, the bytes having been first decoded using a
  117.     platform-dependent encoding or using the specified encoding if given.
  118.  
  119.     buffering is an optional integer used to set the buffering policy. By
  120.     default full buffering is on. Pass 0 to switch buffering off (only
  121.     allowed in binary mode), 1 to set line buffering, and an integer > 1
  122.     for full buffering.
  123.  
  124.     encoding is the name of the encoding used to decode or encode the
  125.     file. This should only be used in text mode. The default encoding is
  126.     platform dependent, but any encoding supported by Python can be
  127.     passed.  See the codecs module for the list of supported encodings.
  128.  
  129.     errors is an optional string that specifies how encoding errors are to
  130.     be handled---this argument should not be used in binary mode. Pass
  131.     'strict' to raise a ValueError exception if there is an encoding error
  132.     (the default of None has the same effect), or pass 'ignore' to ignore
  133.     errors. (Note that ignoring encoding errors can lead to data loss.)
  134.     See the documentation for codecs.register for a list of the permitted
  135.     encoding error strings.
  136.  
  137.     newline controls how universal newlines works (it only applies to text
  138.     mode). It can be None, '', '\\n', '\\r', and '\\r\\n'.  It works as
  139.     follows:
  140.  
  141.     * On input, if newline is None, universal newlines mode is
  142.       enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and
  143.       these are translated into '\\n' before being returned to the
  144.       caller. If it is '', universal newline mode is enabled, but line
  145.       endings are returned to the caller untranslated. If it has any of
  146.       the other legal values, input lines are only terminated by the given
  147.       string, and the line ending is returned to the caller untranslated.
  148.  
  149.     * On output, if newline is None, any '\\n' characters written are
  150.       translated to the system default line separator, os.linesep. If
  151.       newline is '', no translation takes place. If newline is any of the
  152.       other legal values, any '\\n' characters written are translated to
  153.       the given string.
  154.  
  155.     If closefd is False, the underlying file descriptor will be kept open
  156.     when the file is closed. This does not work when a file name is given
  157.     and must be True in that case.
  158.  
  159.     open() returns a file object whose type depends on the mode, and
  160.     through which the standard file operations such as reading and writing
  161.     are performed. When open() is used to open a file in a text mode ('w',
  162.     'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
  163.     a file in a binary mode, the returned class varies: in read binary
  164.     mode, it returns a BufferedReader; in write binary and append binary
  165.     modes, it returns a BufferedWriter, and in read/write mode, it returns
  166.     a BufferedRandom.
  167.  
  168.     It is also possible to use a string or bytearray as a file for both
  169.     reading and writing. For strings StringIO can be used like a file
  170.     opened in a text mode, and for bytes a BytesIO can be used like a file
  171.     opened in a binary mode.
  172.     """
  173.     if not isinstance(file, (basestring, int)):
  174.         raise TypeError('invalid file: %r' % file)
  175.     isinstance(file, (basestring, int))
  176.     if not isinstance(mode, basestring):
  177.         raise TypeError('invalid mode: %r' % mode)
  178.     isinstance(mode, basestring)
  179.     if buffering is not None and not isinstance(buffering, int):
  180.         raise TypeError('invalid buffering: %r' % buffering)
  181.     not isinstance(buffering, int)
  182.     if encoding is not None and not isinstance(encoding, basestring):
  183.         raise TypeError('invalid encoding: %r' % encoding)
  184.     not isinstance(encoding, basestring)
  185.     if errors is not None and not isinstance(errors, basestring):
  186.         raise TypeError('invalid errors: %r' % errors)
  187.     not isinstance(errors, basestring)
  188.     modes = set(mode)
  189.     if modes - set('arwb+tU') or len(mode) > len(modes):
  190.         raise ValueError('invalid mode: %r' % mode)
  191.     len(mode) > len(modes)
  192.     reading = 'r' in modes
  193.     writing = 'w' in modes
  194.     appending = 'a' in modes
  195.     updating = '+' in modes
  196.     text = 't' in modes
  197.     binary = 'b' in modes
  198.     if 'U' in modes:
  199.         if writing or appending:
  200.             raise ValueError("can't use U and writing mode at once")
  201.         appending
  202.         reading = True
  203.     
  204.     if text and binary:
  205.         raise ValueError("can't have text and binary mode at once")
  206.     binary
  207.     if reading + writing + appending > 1:
  208.         raise ValueError("can't have read/write/append mode at once")
  209.     reading + writing + appending > 1
  210.     if not reading and writing or appending:
  211.         raise ValueError('must have exactly one of read/write/append mode')
  212.     appending
  213.     if binary and encoding is not None:
  214.         raise ValueError("binary mode doesn't take an encoding argument")
  215.     encoding is not None
  216.     if binary and errors is not None:
  217.         raise ValueError("binary mode doesn't take an errors argument")
  218.     errors is not None
  219.     if binary and newline is not None:
  220.         raise ValueError("binary mode doesn't take a newline argument")
  221.     newline is not None
  222.     raw = None(None, FileIO + file + '' if not reading or 'r' else '' + '' if not appending or 'a' else '', closefd)
  223.     if buffering is None:
  224.         buffering = -1
  225.     
  226.     line_buffering = False
  227.     if (buffering == 1 or buffering < 0) and raw.isatty():
  228.         buffering = -1
  229.         line_buffering = True
  230.     
  231.     if buffering < 0:
  232.         buffering = DEFAULT_BUFFER_SIZE
  233.         
  234.         try:
  235.             bs = os.fstat(raw.fileno()).st_blksize
  236.         except (os.error, AttributeError):
  237.             pass
  238.  
  239.         if bs > 1:
  240.             buffering = bs
  241.         
  242.     
  243.     if buffering < 0:
  244.         raise ValueError('invalid buffering size')
  245.     buffering < 0
  246.     if buffering == 0:
  247.         if binary:
  248.             return raw
  249.         raise ValueError("can't have unbuffered text I/O")
  250.     buffering == 0
  251.     if updating:
  252.         buffer = BufferedRandom(raw, buffering)
  253.     elif writing or appending:
  254.         buffer = BufferedWriter(raw, buffering)
  255.     elif reading:
  256.         buffer = BufferedReader(raw, buffering)
  257.     else:
  258.         raise ValueError('unknown mode: %r' % mode)
  259.     if appending:
  260.         return buffer
  261.     text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
  262.     text.mode = mode
  263.     return text
  264.  
  265.  
  266. class _DocDescriptor:
  267.     '''Helper for builtins.open.__doc__
  268.     '''
  269.     
  270.     def __get__(self, obj, typ):
  271.         return "open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)\n\n" + open.__doc__
  272.  
  273.  
  274.  
  275. class OpenWrapper:
  276.     """Wrapper for builtins.open
  277.  
  278.     Trick so that open won't become a bound method when stored
  279.     as a class variable (as dumbdbm does).
  280.  
  281.     See initstdio() in Python/pythonrun.c.
  282.     """
  283.     __doc__ = _DocDescriptor()
  284.     
  285.     def __new__(cls, *args, **kwargs):
  286.         return open(*args, **kwargs)
  287.  
  288.  
  289.  
  290. class UnsupportedOperation(ValueError, IOError):
  291.     pass
  292.  
  293.  
  294. class IOBase(object):
  295.     """The abstract base class for all I/O classes, acting on streams of
  296.     bytes. There is no public constructor.
  297.  
  298.     This class provides dummy implementations for many methods that
  299.     derived classes can override selectively; the default implementations
  300.     represent a file that cannot be read, written or seeked.
  301.  
  302.     Even though IOBase does not declare read, readinto, or write because
  303.     their signatures will vary, implementations and clients should
  304.     consider those methods part of the interface. Also, implementations
  305.     may raise a IOError when operations they do not support are called.
  306.  
  307.     The basic type used for binary data read from or written to a file is
  308.     bytes. bytearrays are accepted too, and in some cases (such as
  309.     readinto) needed. Text I/O classes work with str data.
  310.  
  311.     Note that calling any method (even inquiries) on a closed stream is
  312.     undefined. Implementations may raise IOError in this case.
  313.  
  314.     IOBase (and its subclasses) support the iterator protocol, meaning
  315.     that an IOBase object can be iterated over yielding the lines in a
  316.     stream.
  317.  
  318.     IOBase also supports the :keyword:`with` statement. In this example,
  319.     fp is closed after the suite of the with statment is complete:
  320.  
  321.     with open('spam.txt', 'r') as fp:
  322.         fp.write('Spam and eggs!')
  323.     """
  324.     __metaclass__ = abc.ABCMeta
  325.     
  326.     def _unsupported(self, name):
  327.         '''Internal: raise an exception for unsupported operations.'''
  328.         raise UnsupportedOperation('%s.%s() not supported' % (self.__class__.__name__, name))
  329.  
  330.     
  331.     def seek(self, pos, whence = 0):
  332.         '''Change stream position.
  333.  
  334.         Change the stream position to byte offset offset. offset is
  335.         interpreted relative to the position indicated by whence.  Values
  336.         for whence are:
  337.  
  338.         * 0 -- start of stream (the default); offset should be zero or positive
  339.         * 1 -- current stream position; offset may be negative
  340.         * 2 -- end of stream; offset is usually negative
  341.  
  342.         Return the new absolute position.
  343.         '''
  344.         self._unsupported('seek')
  345.  
  346.     
  347.     def tell(self):
  348.         '''Return current stream position.'''
  349.         return self.seek(0, 1)
  350.  
  351.     
  352.     def truncate(self, pos = None):
  353.         '''Truncate file to size bytes.
  354.  
  355.         Size defaults to the current IO position as reported by tell().  Return
  356.         the new size.
  357.         '''
  358.         self._unsupported('truncate')
  359.  
  360.     
  361.     def flush(self):
  362.         '''Flush write buffers, if applicable.
  363.  
  364.         This is not implemented for read-only and non-blocking streams.
  365.         '''
  366.         pass
  367.  
  368.     __closed = False
  369.     
  370.     def close(self):
  371.         '''Flush and close the IO object.
  372.  
  373.         This method has no effect if the file is already closed.
  374.         '''
  375.         if not self._IOBase__closed:
  376.             
  377.             try:
  378.                 self.flush()
  379.             except IOError:
  380.                 pass
  381.  
  382.             self._IOBase__closed = True
  383.         
  384.  
  385.     
  386.     def __del__(self):
  387.         '''Destructor.  Calls close().'''
  388.         
  389.         try:
  390.             self.close()
  391.         except:
  392.             pass
  393.  
  394.  
  395.     
  396.     def seekable(self):
  397.         '''Return whether object supports random access.
  398.  
  399.         If False, seek(), tell() and truncate() will raise IOError.
  400.         This method may need to do a test seek().
  401.         '''
  402.         return False
  403.  
  404.     
  405.     def _checkSeekable(self, msg = None):
  406.         '''Internal: raise an IOError if file is not seekable
  407.         '''
  408.         if not self.seekable():
  409.             raise None(IOError if msg is None else msg)
  410.         self.seekable()
  411.  
  412.     
  413.     def readable(self):
  414.         '''Return whether object was opened for reading.
  415.  
  416.         If False, read() will raise IOError.
  417.         '''
  418.         return False
  419.  
  420.     
  421.     def _checkReadable(self, msg = None):
  422.         '''Internal: raise an IOError if file is not readable
  423.         '''
  424.         if not self.readable():
  425.             raise None(IOError if msg is None else msg)
  426.         self.readable()
  427.  
  428.     
  429.     def writable(self):
  430.         '''Return whether object was opened for writing.
  431.  
  432.         If False, write() and truncate() will raise IOError.
  433.         '''
  434.         return False
  435.  
  436.     
  437.     def _checkWritable(self, msg = None):
  438.         '''Internal: raise an IOError if file is not writable
  439.         '''
  440.         if not self.writable():
  441.             raise None(IOError if msg is None else msg)
  442.         self.writable()
  443.  
  444.     
  445.     def closed(self):
  446.         '''closed: bool.  True iff the file has been closed.
  447.  
  448.         For backwards compatibility, this is a property, not a predicate.
  449.         '''
  450.         return self._IOBase__closed
  451.  
  452.     closed = property(closed)
  453.     
  454.     def _checkClosed(self, msg = None):
  455.         '''Internal: raise an ValueError if file is closed
  456.         '''
  457.         if self.closed:
  458.             raise None(ValueError if msg is None else msg)
  459.         self.closed
  460.  
  461.     
  462.     def __enter__(self):
  463.         '''Context management protocol.  Returns self.'''
  464.         self._checkClosed()
  465.         return self
  466.  
  467.     
  468.     def __exit__(self, *args):
  469.         '''Context management protocol.  Calls close()'''
  470.         self.close()
  471.  
  472.     
  473.     def fileno(self):
  474.         '''Returns underlying file descriptor if one exists.
  475.  
  476.         An IOError is raised if the IO object does not use a file descriptor.
  477.         '''
  478.         self._unsupported('fileno')
  479.  
  480.     
  481.     def isatty(self):
  482.         """Return whether this is an 'interactive' stream.
  483.  
  484.         Return False if it can't be determined.
  485.         """
  486.         self._checkClosed()
  487.         return False
  488.  
  489.     
  490.     def readline(self, limit = -1):
  491.         """Read and return a line from the stream.
  492.  
  493.         If limit is specified, at most limit bytes will be read.
  494.  
  495.         The line terminator is always b'\\n' for binary files; for text
  496.         files, the newlines argument to open can be used to select the line
  497.         terminator(s) recognized.
  498.         """
  499.         self._checkClosed()
  500.         if hasattr(self, 'peek'):
  501.             
  502.             def nreadahead():
  503.                 readahead = self.peek(1)
  504.                 n = readahead if not readahead else len(readahead)
  505.                 if limit >= 0:
  506.                     n = min(n, limit)
  507.                 
  508.                 return n
  509.  
  510.         else:
  511.             
  512.             def nreadahead():
  513.                 return 1
  514.  
  515.         if limit is None:
  516.             limit = -1
  517.         
  518.         if not isinstance(limit, (int, long)):
  519.             raise TypeError('limit must be an integer')
  520.         isinstance(limit, (int, long))
  521.         res = bytearray()
  522.         while limit < 0 or len(res) < limit:
  523.             b = self.read(nreadahead())
  524.             if not b:
  525.                 break
  526.             
  527.             res += b
  528.             if res.endswith(b'\n'):
  529.                 break
  530.                 continue
  531.         return bytes(res)
  532.  
  533.     
  534.     def __iter__(self):
  535.         self._checkClosed()
  536.         return self
  537.  
  538.     
  539.     def next(self):
  540.         line = self.readline()
  541.         if not line:
  542.             raise StopIteration
  543.         line
  544.         return line
  545.  
  546.     
  547.     def readlines(self, hint = None):
  548.         '''Return a list of lines from the stream.
  549.  
  550.         hint can be specified to control the number of lines read: no more
  551.         lines will be read if the total size (in bytes/characters) of all
  552.         lines so far exceeds hint.
  553.         '''
  554.         if hint is None:
  555.             hint = -1
  556.         
  557.         if not isinstance(hint, (int, long)):
  558.             raise TypeError('hint must be an integer')
  559.         isinstance(hint, (int, long))
  560.         if hint <= 0:
  561.             return list(self)
  562.         n = 0
  563.         lines = []
  564.         for line in self:
  565.             lines.append(line)
  566.             n += len(line)
  567.             if n >= hint:
  568.                 break
  569.                 continue
  570.             hint <= 0
  571.         
  572.         return lines
  573.  
  574.     
  575.     def writelines(self, lines):
  576.         self._checkClosed()
  577.         for line in lines:
  578.             self.write(line)
  579.         
  580.  
  581.  
  582.  
  583. class RawIOBase(IOBase):
  584.     '''Base class for raw binary I/O.'''
  585.     
  586.     def read(self, n = -1):
  587.         '''Read and return up to n bytes.
  588.  
  589.         Returns an empty bytes array on EOF, or None if the object is
  590.         set not to block and has no data to read.
  591.         '''
  592.         if n is None:
  593.             n = -1
  594.         
  595.         if n < 0:
  596.             return self.readall()
  597.         b = bytearray(n.__index__())
  598.         n = self.readinto(b)
  599.         del b[n:]
  600.         return bytes(b)
  601.  
  602.     
  603.     def readall(self):
  604.         '''Read until EOF, using multiple read() call.'''
  605.         res = bytearray()
  606.         while True:
  607.             data = self.read(DEFAULT_BUFFER_SIZE)
  608.             if not data:
  609.                 break
  610.             
  611.             res += data
  612.         return bytes(res)
  613.  
  614.     
  615.     def readinto(self, b):
  616.         '''Read up to len(b) bytes into b.
  617.  
  618.         Returns number of bytes read (0 for EOF), or None if the object
  619.         is set not to block as has no data to read.
  620.         '''
  621.         self._unsupported('readinto')
  622.  
  623.     
  624.     def write(self, b):
  625.         '''Write the given buffer to the IO stream.
  626.  
  627.         Returns the number of bytes written, which may be less than len(b).
  628.         '''
  629.         self._unsupported('write')
  630.  
  631.  
  632.  
  633. class FileIO(_fileio._FileIO, RawIOBase):
  634.     '''Raw I/O implementation for OS files.'''
  635.     
  636.     def __init__(self, name, mode = 'r', closefd = True):
  637.         _fileio._FileIO.__init__(self, name, mode, closefd)
  638.         self._name = name
  639.  
  640.     
  641.     def close(self):
  642.         _fileio._FileIO.close(self)
  643.         RawIOBase.close(self)
  644.  
  645.     
  646.     def name(self):
  647.         return self._name
  648.  
  649.     name = property(name)
  650.  
  651.  
  652. class BufferedIOBase(IOBase):
  653.     '''Base class for buffered IO objects.
  654.  
  655.     The main difference with RawIOBase is that the read() method
  656.     supports omitting the size argument, and does not have a default
  657.     implementation that defers to readinto().
  658.  
  659.     In addition, read(), readinto() and write() may raise
  660.     BlockingIOError if the underlying raw stream is in non-blocking
  661.     mode and not ready; unlike their raw counterparts, they will never
  662.     return None.
  663.  
  664.     A typical implementation should not inherit from a RawIOBase
  665.     implementation, but wrap one.
  666.     '''
  667.     
  668.     def read(self, n = None):
  669.         """Read and return up to n bytes.
  670.  
  671.         If the argument is omitted, None, or negative, reads and
  672.         returns all data until EOF.
  673.  
  674.         If the argument is positive, and the underlying raw stream is
  675.         not 'interactive', multiple raw reads may be issued to satisfy
  676.         the byte count (unless EOF is reached first).  But for
  677.         interactive raw streams (XXX and for pipes?), at most one raw
  678.         read will be issued, and a short result does not imply that
  679.         EOF is imminent.
  680.  
  681.         Returns an empty bytes array on EOF.
  682.  
  683.         Raises BlockingIOError if the underlying raw stream has no
  684.         data at the moment.
  685.         """
  686.         self._unsupported('read')
  687.  
  688.     
  689.     def readinto(self, b):
  690.         """Read up to len(b) bytes into b.
  691.  
  692.         Like read(), this may issue multiple reads to the underlying raw
  693.         stream, unless the latter is 'interactive'.
  694.  
  695.         Returns the number of bytes read (0 for EOF).
  696.  
  697.         Raises BlockingIOError if the underlying raw stream has no
  698.         data at the moment.
  699.         """
  700.         data = self.read(len(b))
  701.         n = len(data)
  702.         
  703.         try:
  704.             b[:n] = data
  705.         except TypeError:
  706.             err = None
  707.             import array as array
  708.             if not isinstance(b, array.array):
  709.                 raise err
  710.             isinstance(b, array.array)
  711.             b[:n] = array.array(b'b', data)
  712.  
  713.         return n
  714.  
  715.     
  716.     def write(self, b):
  717.         '''Write the given buffer to the IO stream.
  718.  
  719.         Return the number of bytes written, which is never less than
  720.         len(b).
  721.  
  722.         Raises BlockingIOError if the buffer is full and the
  723.         underlying raw stream cannot accept more data at the moment.
  724.         '''
  725.         self._unsupported('write')
  726.  
  727.  
  728.  
  729. class _BufferedIOMixin(BufferedIOBase):
  730.     '''A mixin implementation of BufferedIOBase with an underlying raw stream.
  731.  
  732.     This passes most requests on to the underlying raw stream.  It
  733.     does *not* provide implementations of read(), readinto() or
  734.     write().
  735.     '''
  736.     
  737.     def __init__(self, raw):
  738.         self.raw = raw
  739.  
  740.     
  741.     def seek(self, pos, whence = 0):
  742.         return self.raw.seek(pos, whence)
  743.  
  744.     
  745.     def tell(self):
  746.         return self.raw.tell()
  747.  
  748.     
  749.     def truncate(self, pos = None):
  750.         self.flush()
  751.         if pos is None:
  752.             pos = self.tell()
  753.         
  754.         return self.raw.truncate(pos)
  755.  
  756.     
  757.     def flush(self):
  758.         self.raw.flush()
  759.  
  760.     
  761.     def close(self):
  762.         if not self.closed:
  763.             
  764.             try:
  765.                 self.flush()
  766.             except IOError:
  767.                 pass
  768.  
  769.             self.raw.close()
  770.         
  771.  
  772.     
  773.     def seekable(self):
  774.         return self.raw.seekable()
  775.  
  776.     
  777.     def readable(self):
  778.         return self.raw.readable()
  779.  
  780.     
  781.     def writable(self):
  782.         return self.raw.writable()
  783.  
  784.     
  785.     def closed(self):
  786.         return self.raw.closed
  787.  
  788.     closed = property(closed)
  789.     
  790.     def name(self):
  791.         return self.raw.name
  792.  
  793.     name = property(name)
  794.     
  795.     def mode(self):
  796.         return self.raw.mode
  797.  
  798.     mode = property(mode)
  799.     
  800.     def fileno(self):
  801.         return self.raw.fileno()
  802.  
  803.     
  804.     def isatty(self):
  805.         return self.raw.isatty()
  806.  
  807.  
  808.  
  809. class _BytesIO(BufferedIOBase):
  810.     '''Buffered I/O implementation using an in-memory bytes buffer.'''
  811.     
  812.     def __init__(self, initial_bytes = None):
  813.         buf = bytearray()
  814.         if initial_bytes is not None:
  815.             buf += bytearray(initial_bytes)
  816.         
  817.         self._buffer = buf
  818.         self._pos = 0
  819.  
  820.     
  821.     def getvalue(self):
  822.         '''Return the bytes value (contents) of the buffer
  823.         '''
  824.         if self.closed:
  825.             raise ValueError('getvalue on closed file')
  826.         self.closed
  827.         return bytes(self._buffer)
  828.  
  829.     
  830.     def read(self, n = None):
  831.         if self.closed:
  832.             raise ValueError('read from closed file')
  833.         self.closed
  834.         if n is None:
  835.             n = -1
  836.         
  837.         if not isinstance(n, (int, long)):
  838.             raise TypeError('argument must be an integer')
  839.         isinstance(n, (int, long))
  840.         if n < 0:
  841.             n = len(self._buffer)
  842.         
  843.         if len(self._buffer) <= self._pos:
  844.             return b''
  845.         newpos = min(len(self._buffer), self._pos + n)
  846.         b = self._buffer[self._pos:newpos]
  847.         self._pos = newpos
  848.         return bytes(b)
  849.  
  850.     
  851.     def read1(self, n):
  852.         '''this is the same as read.
  853.         '''
  854.         return self.read(n)
  855.  
  856.     
  857.     def write(self, b):
  858.         if self.closed:
  859.             raise ValueError('write to closed file')
  860.         self.closed
  861.         if isinstance(b, unicode):
  862.             raise TypeError("can't write unicode to binary stream")
  863.         isinstance(b, unicode)
  864.         n = len(b)
  865.         if n == 0:
  866.             return 0
  867.         pos = self._pos
  868.         self._buffer[pos:pos + n] = b
  869.         self._pos += n
  870.         return n
  871.  
  872.     
  873.     def seek(self, pos, whence = 0):
  874.         if self.closed:
  875.             raise ValueError('seek on closed file')
  876.         self.closed
  877.         
  878.         try:
  879.             pos = pos.__index__()
  880.         except AttributeError:
  881.             err = None
  882.             raise TypeError('an integer is required')
  883.  
  884.         if whence == 0:
  885.             if pos < 0:
  886.                 raise ValueError('negative seek position %r' % (pos,))
  887.             pos < 0
  888.             self._pos = pos
  889.         elif whence == 1:
  890.             self._pos = max(0, self._pos + pos)
  891.         elif whence == 2:
  892.             self._pos = max(0, len(self._buffer) + pos)
  893.         else:
  894.             raise ValueError('invalid whence value')
  895.         return (whence == 0)._pos
  896.  
  897.     
  898.     def tell(self):
  899.         if self.closed:
  900.             raise ValueError('tell on closed file')
  901.         self.closed
  902.         return self._pos
  903.  
  904.     
  905.     def truncate(self, pos = None):
  906.         if self.closed:
  907.             raise ValueError('truncate on closed file')
  908.         self.closed
  909.         if pos is None:
  910.             pos = self._pos
  911.         elif pos < 0:
  912.             raise ValueError('negative truncate position %r' % (pos,))
  913.         
  914.         del self._buffer[pos:]
  915.         return self.seek(pos)
  916.  
  917.     
  918.     def readable(self):
  919.         return True
  920.  
  921.     
  922.     def writable(self):
  923.         return True
  924.  
  925.     
  926.     def seekable(self):
  927.         return True
  928.  
  929.  
  930.  
  931. try:
  932.     import _bytesio
  933.     
  934.     class BytesIO(_bytesio._BytesIO, BufferedIOBase):
  935.         __doc__ = _bytesio._BytesIO.__doc__
  936.  
  937. except ImportError:
  938.     BytesIO = _BytesIO
  939.  
  940.  
  941. class BufferedReader(_BufferedIOMixin):
  942.     '''BufferedReader(raw[, buffer_size])
  943.  
  944.     A buffer for a readable, sequential BaseRawIO object.
  945.  
  946.     The constructor creates a BufferedReader for the given readable raw
  947.     stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
  948.     is used.
  949.     '''
  950.     
  951.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE):
  952.         '''Create a new buffered reader using the given readable raw IO object.
  953.         '''
  954.         raw._checkReadable()
  955.         _BufferedIOMixin.__init__(self, raw)
  956.         self.buffer_size = buffer_size
  957.         self._reset_read_buf()
  958.         self._read_lock = threading.Lock()
  959.  
  960.     
  961.     def _reset_read_buf(self):
  962.         self._read_buf = b''
  963.         self._read_pos = 0
  964.  
  965.     
  966.     def read(self, n = None):
  967.         '''Read n bytes.
  968.  
  969.         Returns exactly n bytes of data unless the underlying raw IO
  970.         stream reaches EOF or if the call would block in non-blocking
  971.         mode. If n is negative, read until EOF or until read() would
  972.         block.
  973.         '''
  974.         self._read_lock.__enter__()
  975.         
  976.         try:
  977.             return self._read_unlocked(n)
  978.         finally:
  979.             pass
  980.  
  981.  
  982.     
  983.     def _read_unlocked(self, n = None):
  984.         nodata_val = b''
  985.         empty_values = (b'', None)
  986.         buf = self._read_buf
  987.         pos = self._read_pos
  988.         if n is None or n == -1:
  989.             self._reset_read_buf()
  990.             chunks = [
  991.                 buf[pos:]]
  992.             current_size = 0
  993.             while True:
  994.                 chunk = self.raw.read()
  995.                 if chunk in empty_values:
  996.                     nodata_val = chunk
  997.                     break
  998.                 
  999.                 current_size += len(chunk)
  1000.                 chunks.append(chunk)
  1001.             if not b''.join(chunks):
  1002.                 pass
  1003.             return nodata_val
  1004.         avail = len(buf) - pos
  1005.         if n <= avail:
  1006.             self._read_pos += n
  1007.             return buf[pos:pos + n]
  1008.         chunks = [
  1009.             buf[pos:]]
  1010.         wanted = max(self.buffer_size, n)
  1011.         while avail < n:
  1012.             chunk = self.raw.read(wanted)
  1013.             avail += len(chunk)
  1014.             chunks.append(chunk)
  1015.             continue
  1016.             None if chunk in empty_values else n == -1
  1017.         n = min(n, avail)
  1018.         out = b''.join(chunks)
  1019.         self._read_buf = out[n:]
  1020.         self._read_pos = 0
  1021.         if out:
  1022.             return out[:n]
  1023.         return nodata_val
  1024.  
  1025.     
  1026.     def peek(self, n = 0):
  1027.         '''Returns buffered bytes without advancing the position.
  1028.  
  1029.         The argument indicates a desired minimal number of bytes; we
  1030.         do at most one raw read to satisfy it.  We never return more
  1031.         than self.buffer_size.
  1032.         '''
  1033.         self._read_lock.__enter__()
  1034.         
  1035.         try:
  1036.             return self._peek_unlocked(n)
  1037.         finally:
  1038.             pass
  1039.  
  1040.  
  1041.     
  1042.     def _peek_unlocked(self, n = 0):
  1043.         want = min(n, self.buffer_size)
  1044.         have = len(self._read_buf) - self._read_pos
  1045.         if have < want:
  1046.             to_read = self.buffer_size - have
  1047.             current = self.raw.read(to_read)
  1048.             if current:
  1049.                 self._read_buf = self._read_buf[self._read_pos:] + current
  1050.                 self._read_pos = 0
  1051.             
  1052.         
  1053.         return self._read_buf[self._read_pos:]
  1054.  
  1055.     
  1056.     def read1(self, n):
  1057.         '''Reads up to n bytes, with at most one read() system call.'''
  1058.         if n <= 0:
  1059.             return b''
  1060.         self._read_lock.__enter__()
  1061.         
  1062.         try:
  1063.             self._peek_unlocked(1)
  1064.             return self._read_unlocked(min(n, len(self._read_buf) - self._read_pos))
  1065.         finally:
  1066.             pass
  1067.  
  1068.  
  1069.     
  1070.     def tell(self):
  1071.         return (self.raw.tell() - len(self._read_buf)) + self._read_pos
  1072.  
  1073.     
  1074.     def seek(self, pos, whence = 0):
  1075.         self._read_lock.__enter__()
  1076.         
  1077.         try:
  1078.             pos = self.raw.seek(pos, whence)
  1079.             self._reset_read_buf()
  1080.             return pos
  1081.         finally:
  1082.             pass
  1083.  
  1084.  
  1085.  
  1086.  
  1087. class BufferedWriter(_BufferedIOMixin):
  1088.     '''A buffer for a writeable sequential RawIO object.
  1089.  
  1090.     The constructor creates a BufferedWriter for the given writeable raw
  1091.     stream. If the buffer_size is not given, it defaults to
  1092.     DEAFULT_BUFFER_SIZE. If max_buffer_size is omitted, it defaults to
  1093.     twice the buffer size.
  1094.     '''
  1095.     
  1096.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1097.         raw._checkWritable()
  1098.         _BufferedIOMixin.__init__(self, raw)
  1099.         self.buffer_size = buffer_size
  1100.         self.max_buffer_size = None if max_buffer_size is None else max_buffer_size
  1101.         self._write_buf = bytearray()
  1102.         self._write_lock = threading.Lock()
  1103.  
  1104.     
  1105.     def write(self, b):
  1106.         if self.closed:
  1107.             raise ValueError('write to closed file')
  1108.         self.closed
  1109.         if isinstance(b, unicode):
  1110.             raise TypeError("can't write unicode to binary stream")
  1111.         isinstance(b, unicode)
  1112.         self._write_lock.__enter__()
  1113.         
  1114.         try:
  1115.             if len(self._write_buf) > self.buffer_size:
  1116.                 
  1117.                 try:
  1118.                     self._flush_unlocked()
  1119.                 except BlockingIOError:
  1120.                     self._write_lock.__exit__
  1121.                     e = self._write_lock.__exit__
  1122.                     self._write_lock
  1123.                     raise BlockingIOError(e.errno, e.strerror, 0)
  1124.                 except:
  1125.                     self._write_lock.__exit__<EXCEPTION MATCH>BlockingIOError
  1126.                 
  1127.  
  1128.             self._write_lock.__exit__
  1129.             before = len(self._write_buf)
  1130.             self._write_buf.extend(b)
  1131.             written = len(self._write_buf) - before
  1132.             if len(self._write_buf) > self.buffer_size:
  1133.                 
  1134.                 try:
  1135.                     self._flush_unlocked()
  1136.                 except BlockingIOError:
  1137.                     self._write_lock.__exit__
  1138.                     e = self._write_lock.__exit__
  1139.                     self._write_lock
  1140.                     if len(self._write_buf) > self.max_buffer_size:
  1141.                         overage = len(self._write_buf) - self.max_buffer_size
  1142.                         self._write_buf = self._write_buf[:self.max_buffer_size]
  1143.                         raise BlockingIOError(e.errno, e.strerror, overage)
  1144.                     len(self._write_buf) > self.max_buffer_size
  1145.                 except:
  1146.                     self._write_lock.__exit__<EXCEPTION MATCH>BlockingIOError
  1147.                 
  1148.  
  1149.             self._write_lock.__exit__
  1150.             return written
  1151.         finally:
  1152.             pass
  1153.  
  1154.  
  1155.     
  1156.     def truncate(self, pos = None):
  1157.         self._write_lock.__enter__()
  1158.         
  1159.         try:
  1160.             self._flush_unlocked()
  1161.             return self.raw.truncate(pos)
  1162.         finally:
  1163.             pass
  1164.  
  1165.  
  1166.     
  1167.     def flush(self):
  1168.         self._write_lock.__enter__()
  1169.         
  1170.         try:
  1171.             self._flush_unlocked()
  1172.         finally:
  1173.             pass
  1174.  
  1175.  
  1176.     
  1177.     def _flush_unlocked(self):
  1178.         if self.closed:
  1179.             raise ValueError('flush of closed file')
  1180.         self.closed
  1181.         written = 0
  1182.         
  1183.         try:
  1184.             while self._write_buf:
  1185.                 n = self.raw.write(self._write_buf)
  1186.                 del self._write_buf[:n]
  1187.                 written += n
  1188.         except BlockingIOError:
  1189.             e = None
  1190.             n = e.characters_written
  1191.             del self._write_buf[:n]
  1192.             written += n
  1193.             raise BlockingIOError(e.errno, e.strerror, written)
  1194.  
  1195.  
  1196.     
  1197.     def tell(self):
  1198.         return self.raw.tell() + len(self._write_buf)
  1199.  
  1200.     
  1201.     def seek(self, pos, whence = 0):
  1202.         self._write_lock.__enter__()
  1203.         
  1204.         try:
  1205.             self._flush_unlocked()
  1206.             return self.raw.seek(pos, whence)
  1207.         finally:
  1208.             pass
  1209.  
  1210.  
  1211.  
  1212.  
  1213. class BufferedRWPair(BufferedIOBase):
  1214.     '''A buffered reader and writer object together.
  1215.  
  1216.     A buffered reader object and buffered writer object put together to
  1217.     form a sequential IO object that can read and write. This is typically
  1218.     used with a socket or two-way pipe.
  1219.  
  1220.     reader and writer are RawIOBase objects that are readable and
  1221.     writeable respectively. If the buffer_size is omitted it defaults to
  1222.     DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered writer)
  1223.     defaults to twice the buffer size.
  1224.     '''
  1225.     
  1226.     def __init__(self, reader, writer, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1227.         '''Constructor.
  1228.  
  1229.         The arguments are two RawIO instances.
  1230.         '''
  1231.         reader._checkReadable()
  1232.         writer._checkWritable()
  1233.         self.reader = BufferedReader(reader, buffer_size)
  1234.         self.writer = BufferedWriter(writer, buffer_size, max_buffer_size)
  1235.  
  1236.     
  1237.     def read(self, n = None):
  1238.         if n is None:
  1239.             n = -1
  1240.         
  1241.         return self.reader.read(n)
  1242.  
  1243.     
  1244.     def readinto(self, b):
  1245.         return self.reader.readinto(b)
  1246.  
  1247.     
  1248.     def write(self, b):
  1249.         return self.writer.write(b)
  1250.  
  1251.     
  1252.     def peek(self, n = 0):
  1253.         return self.reader.peek(n)
  1254.  
  1255.     
  1256.     def read1(self, n):
  1257.         return self.reader.read1(n)
  1258.  
  1259.     
  1260.     def readable(self):
  1261.         return self.reader.readable()
  1262.  
  1263.     
  1264.     def writable(self):
  1265.         return self.writer.writable()
  1266.  
  1267.     
  1268.     def flush(self):
  1269.         return self.writer.flush()
  1270.  
  1271.     
  1272.     def close(self):
  1273.         self.writer.close()
  1274.         self.reader.close()
  1275.  
  1276.     
  1277.     def isatty(self):
  1278.         if not self.reader.isatty():
  1279.             pass
  1280.         return self.writer.isatty()
  1281.  
  1282.     
  1283.     def closed(self):
  1284.         return self.writer.closed
  1285.  
  1286.     closed = property(closed)
  1287.  
  1288.  
  1289. class BufferedRandom(BufferedWriter, BufferedReader):
  1290.     '''A buffered interface to random access streams.
  1291.  
  1292.     The constructor creates a reader and writer for a seekable stream,
  1293.     raw, given in the first argument. If the buffer_size is omitted it
  1294.     defaults to DEFAULT_BUFFER_SIZE. The max_buffer_size (for the buffered
  1295.     writer) defaults to twice the buffer size.
  1296.     '''
  1297.     
  1298.     def __init__(self, raw, buffer_size = DEFAULT_BUFFER_SIZE, max_buffer_size = None):
  1299.         raw._checkSeekable()
  1300.         BufferedReader.__init__(self, raw, buffer_size)
  1301.         BufferedWriter.__init__(self, raw, buffer_size, max_buffer_size)
  1302.  
  1303.     
  1304.     def seek(self, pos, whence = 0):
  1305.         self.flush()
  1306.         pos = self.raw.seek(pos, whence)
  1307.         self._read_lock.__enter__()
  1308.         
  1309.         try:
  1310.             self._reset_read_buf()
  1311.         finally:
  1312.             pass
  1313.  
  1314.         return pos
  1315.  
  1316.     
  1317.     def tell(self):
  1318.         if self._write_buf:
  1319.             return self.raw.tell() + len(self._write_buf)
  1320.         return BufferedReader.tell(self)
  1321.  
  1322.     
  1323.     def truncate(self, pos = None):
  1324.         if pos is None:
  1325.             pos = self.tell()
  1326.         
  1327.         self.seek(pos)
  1328.         return BufferedWriter.truncate(self)
  1329.  
  1330.     
  1331.     def read(self, n = None):
  1332.         if n is None:
  1333.             n = -1
  1334.         
  1335.         self.flush()
  1336.         return BufferedReader.read(self, n)
  1337.  
  1338.     
  1339.     def readinto(self, b):
  1340.         self.flush()
  1341.         return BufferedReader.readinto(self, b)
  1342.  
  1343.     
  1344.     def peek(self, n = 0):
  1345.         self.flush()
  1346.         return BufferedReader.peek(self, n)
  1347.  
  1348.     
  1349.     def read1(self, n):
  1350.         self.flush()
  1351.         return BufferedReader.read1(self, n)
  1352.  
  1353.     
  1354.     def write(self, b):
  1355.         return BufferedWriter.write(self, b)
  1356.  
  1357.  
  1358.  
  1359. class TextIOBase(IOBase):
  1360.     """Base class for text I/O.
  1361.  
  1362.     This class provides a character and line based interface to stream
  1363.     I/O. There is no readinto method because Python's character strings
  1364.     are immutable. There is no public constructor.
  1365.     """
  1366.     
  1367.     def read(self, n = -1):
  1368.         '''Read at most n characters from stream.
  1369.  
  1370.         Read from underlying buffer until we have n characters or we hit EOF.
  1371.         If n is negative or omitted, read until EOF.
  1372.         '''
  1373.         self._unsupported('read')
  1374.  
  1375.     
  1376.     def write(self, s):
  1377.         '''Write string s to stream.'''
  1378.         self._unsupported('write')
  1379.  
  1380.     
  1381.     def truncate(self, pos = None):
  1382.         '''Truncate size to pos.'''
  1383.         self._unsupported('truncate')
  1384.  
  1385.     
  1386.     def readline(self):
  1387.         '''Read until newline or EOF.
  1388.  
  1389.         Returns an empty string if EOF is hit immediately.
  1390.         '''
  1391.         self._unsupported('readline')
  1392.  
  1393.     
  1394.     def encoding(self):
  1395.         '''Subclasses should override.'''
  1396.         pass
  1397.  
  1398.     encoding = property(encoding)
  1399.     
  1400.     def newlines(self):
  1401.         '''Line endings translated so far.
  1402.  
  1403.         Only line endings translated during reading are considered.
  1404.  
  1405.         Subclasses should override.
  1406.         '''
  1407.         pass
  1408.  
  1409.     newlines = property(newlines)
  1410.  
  1411.  
  1412. class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
  1413.     '''Codec used when reading a file in universal newlines mode.
  1414.     It wraps another incremental decoder, translating \\r\\n and \\r into \\n.
  1415.     It also records the types of newlines encountered.
  1416.     When used with translate=False, it ensures that the newline sequence is
  1417.     returned in one piece.
  1418.     '''
  1419.     
  1420.     def __init__(self, decoder, translate, errors = 'strict'):
  1421.         codecs.IncrementalDecoder.__init__(self, errors = errors)
  1422.         self.translate = translate
  1423.         self.decoder = decoder
  1424.         self.seennl = 0
  1425.         self.pendingcr = False
  1426.  
  1427.     
  1428.     def decode(self, input, final = False):
  1429.         output = self.decoder.decode(input, final = final)
  1430.         if self.pendingcr:
  1431.             if output or final:
  1432.                 output = '\r' + output
  1433.                 self.pendingcr = False
  1434.             
  1435.         if output.endswith('\r') and not final:
  1436.             output = output[:-1]
  1437.             self.pendingcr = True
  1438.         
  1439.         crlf = output.count('\r\n')
  1440.         cr = output.count('\r') - crlf
  1441.         lf = output.count('\n') - crlf
  1442.         if crlf:
  1443.             pass
  1444.         self |= self.seennl | self._LF if lf else self._CR | self._CRLF
  1445.         if self.translate:
  1446.             if crlf:
  1447.                 output = output.replace('\r\n', '\n')
  1448.             
  1449.             if cr:
  1450.                 output = output.replace('\r', '\n')
  1451.             
  1452.         
  1453.         return output
  1454.  
  1455.     
  1456.     def getstate(self):
  1457.         (buf, flag) = self.decoder.getstate()
  1458.         flag <<= 1
  1459.         if self.pendingcr:
  1460.             flag |= 1
  1461.         
  1462.         return (buf, flag)
  1463.  
  1464.     
  1465.     def setstate(self, state):
  1466.         (buf, flag) = state
  1467.         self.pendingcr = bool(flag & 1)
  1468.         self.decoder.setstate((buf, flag >> 1))
  1469.  
  1470.     
  1471.     def reset(self):
  1472.         self.seennl = 0
  1473.         self.pendingcr = False
  1474.         self.decoder.reset()
  1475.  
  1476.     _LF = 1
  1477.     _CR = 2
  1478.     _CRLF = 4
  1479.     
  1480.     def newlines(self):
  1481.         return (None, '\n', '\r', ('\r', '\n'), '\r\n', ('\n', '\r\n'), ('\r', '\r\n'), ('\r', '\n', '\r\n'))[self.seennl]
  1482.  
  1483.     newlines = property(newlines)
  1484.  
  1485.  
  1486. class TextIOWrapper(TextIOBase):
  1487.     '''Character and line based layer over a BufferedIOBase object, buffer.
  1488.  
  1489.     encoding gives the name of the encoding that the stream will be
  1490.     decoded or encoded with. It defaults to locale.getpreferredencoding.
  1491.  
  1492.     errors determines the strictness of encoding and decoding (see the
  1493.     codecs.register) and defaults to "strict".
  1494.  
  1495.     newline can be None, \'\', \'\\n\', \'\\r\', or \'\\r\\n\'.  It controls the
  1496.     handling of line endings. If it is None, universal newlines is
  1497.     enabled.  With this enabled, on input, the lines endings \'\\n\', \'\\r\',
  1498.     or \'\\r\\n\' are translated to \'\\n\' before being returned to the
  1499.     caller. Conversely, on output, \'\\n\' is translated to the system
  1500.     default line separator, os.linesep. If newline is any other of its
  1501.     legal values, that newline becomes the newline when the file is read
  1502.     and it is returned untranslated. On output, \'\\n\' is converted to the
  1503.     newline.
  1504.  
  1505.     If line_buffering is True, a call to flush is implied when a call to
  1506.     write contains a newline character.
  1507.     '''
  1508.     _CHUNK_SIZE = 128
  1509.     
  1510.     def __init__(self, buffer, encoding = None, errors = None, newline = None, line_buffering = False):
  1511.         if newline not in (None, '', '\n', '\r', '\r\n'):
  1512.             raise ValueError('illegal newline value: %r' % (newline,))
  1513.         newline not in (None, '', '\n', '\r', '\r\n')
  1514.         if encoding is None:
  1515.             
  1516.             try:
  1517.                 encoding = os.device_encoding(buffer.fileno())
  1518.             except (AttributeError, UnsupportedOperation):
  1519.                 pass
  1520.  
  1521.             if encoding is None:
  1522.                 
  1523.                 try:
  1524.                     import locale as locale
  1525.                 except ImportError:
  1526.                     encoding = 'ascii'
  1527.  
  1528.                 encoding = locale.getpreferredencoding()
  1529.             
  1530.         
  1531.         if not isinstance(encoding, basestring):
  1532.             raise ValueError('invalid encoding: %r' % encoding)
  1533.         isinstance(encoding, basestring)
  1534.         if errors is None:
  1535.             errors = 'strict'
  1536.         elif not isinstance(errors, basestring):
  1537.             raise ValueError('invalid errors: %r' % errors)
  1538.         
  1539.         self.buffer = buffer
  1540.         self._line_buffering = line_buffering
  1541.         self._encoding = encoding
  1542.         self._errors = errors
  1543.         self._readuniversal = not newline
  1544.         self._readtranslate = newline is None
  1545.         self._readnl = newline
  1546.         self._writetranslate = newline != ''
  1547.         if not newline:
  1548.             pass
  1549.         self._writenl = os.linesep
  1550.         self._encoder = None
  1551.         self._decoder = None
  1552.         self._decoded_chars = ''
  1553.         self._decoded_chars_used = 0
  1554.         self._snapshot = None
  1555.         self._seekable = self._telling = self.buffer.seekable()
  1556.  
  1557.     
  1558.     def encoding(self):
  1559.         return self._encoding
  1560.  
  1561.     encoding = property(encoding)
  1562.     
  1563.     def errors(self):
  1564.         return self._errors
  1565.  
  1566.     errors = property(errors)
  1567.     
  1568.     def line_buffering(self):
  1569.         return self._line_buffering
  1570.  
  1571.     line_buffering = property(line_buffering)
  1572.     
  1573.     def seekable(self):
  1574.         return self._seekable
  1575.  
  1576.     
  1577.     def readable(self):
  1578.         return self.buffer.readable()
  1579.  
  1580.     
  1581.     def writable(self):
  1582.         return self.buffer.writable()
  1583.  
  1584.     
  1585.     def flush(self):
  1586.         self.buffer.flush()
  1587.         self._telling = self._seekable
  1588.  
  1589.     
  1590.     def close(self):
  1591.         
  1592.         try:
  1593.             self.flush()
  1594.         except:
  1595.             pass
  1596.  
  1597.         self.buffer.close()
  1598.  
  1599.     
  1600.     def closed(self):
  1601.         return self.buffer.closed
  1602.  
  1603.     closed = property(closed)
  1604.     
  1605.     def name(self):
  1606.         return self.buffer.name
  1607.  
  1608.     name = property(name)
  1609.     
  1610.     def fileno(self):
  1611.         return self.buffer.fileno()
  1612.  
  1613.     
  1614.     def isatty(self):
  1615.         return self.buffer.isatty()
  1616.  
  1617.     
  1618.     def write(self, s):
  1619.         if self.closed:
  1620.             raise ValueError('write to closed file')
  1621.         self.closed
  1622.         if not isinstance(s, unicode):
  1623.             raise TypeError("can't write %s to text stream" % s.__class__.__name__)
  1624.         isinstance(s, unicode)
  1625.         length = len(s)
  1626.         if self._writetranslate or self._line_buffering:
  1627.             pass
  1628.         haslf = '\n' in s
  1629.         if haslf and self._writetranslate and self._writenl != '\n':
  1630.             s = s.replace('\n', self._writenl)
  1631.         
  1632.         if not self._encoder:
  1633.             pass
  1634.         encoder = self._get_encoder()
  1635.         b = encoder.encode(s)
  1636.         self.buffer.write(b)
  1637.         if self._line_buffering:
  1638.             if haslf or '\r' in s:
  1639.                 self.flush()
  1640.             
  1641.         self._snapshot = None
  1642.         if self._decoder:
  1643.             self._decoder.reset()
  1644.         
  1645.         return length
  1646.  
  1647.     
  1648.     def _get_encoder(self):
  1649.         make_encoder = codecs.getincrementalencoder(self._encoding)
  1650.         self._encoder = make_encoder(self._errors)
  1651.         return self._encoder
  1652.  
  1653.     
  1654.     def _get_decoder(self):
  1655.         make_decoder = codecs.getincrementaldecoder(self._encoding)
  1656.         decoder = make_decoder(self._errors)
  1657.         if self._readuniversal:
  1658.             decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
  1659.         
  1660.         self._decoder = decoder
  1661.         return decoder
  1662.  
  1663.     
  1664.     def _set_decoded_chars(self, chars):
  1665.         '''Set the _decoded_chars buffer.'''
  1666.         self._decoded_chars = chars
  1667.         self._decoded_chars_used = 0
  1668.  
  1669.     
  1670.     def _get_decoded_chars(self, n = None):
  1671.         '''Advance into the _decoded_chars buffer.'''
  1672.         offset = self._decoded_chars_used
  1673.         if n is None:
  1674.             chars = self._decoded_chars[offset:]
  1675.         else:
  1676.             chars = self._decoded_chars[offset:offset + n]
  1677.         self._decoded_chars_used += len(chars)
  1678.         return chars
  1679.  
  1680.     
  1681.     def _rewind_decoded_chars(self, n):
  1682.         '''Rewind the _decoded_chars buffer.'''
  1683.         if self._decoded_chars_used < n:
  1684.             raise AssertionError('rewind decoded_chars out of bounds')
  1685.         self._decoded_chars_used < n
  1686.         self._decoded_chars_used -= n
  1687.  
  1688.     
  1689.     def _read_chunk(self):
  1690.         '''
  1691.         Read and decode the next chunk of data from the BufferedReader.
  1692.  
  1693.         The return value is True unless EOF was reached.  The decoded string
  1694.         is placed in self._decoded_chars (replacing its previous value).
  1695.         The entire input chunk is sent to the decoder, though some of it
  1696.         may remain buffered in the decoder, yet to be converted.
  1697.         '''
  1698.         if self._decoder is None:
  1699.             raise ValueError('no decoder')
  1700.         self._decoder is None
  1701.         if self._telling:
  1702.             (dec_buffer, dec_flags) = self._decoder.getstate()
  1703.         
  1704.         input_chunk = self.buffer.read1(self._CHUNK_SIZE)
  1705.         eof = not input_chunk
  1706.         self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
  1707.         if self._telling:
  1708.             self._snapshot = (dec_flags, dec_buffer + input_chunk)
  1709.         
  1710.         return not eof
  1711.  
  1712.     
  1713.     def _pack_cookie(self, position, dec_flags = 0, bytes_to_feed = 0, need_eof = 0, chars_to_skip = 0):
  1714.         return position | dec_flags << 64 | bytes_to_feed << 128 | chars_to_skip << 192 | bool(need_eof) << 256
  1715.  
  1716.     
  1717.     def _unpack_cookie(self, bigint):
  1718.         (rest, position) = divmod(bigint, 0x10000000000000000L)
  1719.         (rest, dec_flags) = divmod(rest, 0x10000000000000000L)
  1720.         (rest, bytes_to_feed) = divmod(rest, 0x10000000000000000L)
  1721.         (need_eof, chars_to_skip) = divmod(rest, 0x10000000000000000L)
  1722.         return (position, dec_flags, bytes_to_feed, need_eof, chars_to_skip)
  1723.  
  1724.     
  1725.     def tell(self):
  1726.         if not self._seekable:
  1727.             raise IOError('underlying stream is not seekable')
  1728.         self._seekable
  1729.         if not self._telling:
  1730.             raise IOError('telling position disabled by next() call')
  1731.         self._telling
  1732.         self.flush()
  1733.         position = self.buffer.tell()
  1734.         decoder = self._decoder
  1735.         if decoder is None or self._snapshot is None:
  1736.             if self._decoded_chars:
  1737.                 raise AssertionError('pending decoded text')
  1738.             self._decoded_chars
  1739.             return position
  1740.         (dec_flags, next_input) = self._snapshot
  1741.         position -= len(next_input)
  1742.         chars_to_skip = self._decoded_chars_used
  1743.         if chars_to_skip == 0:
  1744.             return self._pack_cookie(position, dec_flags)
  1745.         saved_state = decoder.getstate()
  1746.         
  1747.         try:
  1748.             decoder.setstate((b'', dec_flags))
  1749.             start_pos = position
  1750.             start_flags = dec_flags
  1751.             bytes_fed = 0
  1752.             chars_decoded = 0
  1753.             need_eof = 0
  1754.             for next_byte in next_input:
  1755.                 bytes_fed += 1
  1756.                 chars_decoded += len(decoder.decode(next_byte))
  1757.                 (dec_buffer, dec_flags) = decoder.getstate()
  1758.                 if chars_decoded >= chars_to_skip:
  1759.                     break
  1760.                     continue
  1761.                 None if not dec_buffer and chars_decoded <= chars_to_skip else self._snapshot is None
  1762.             else:
  1763.                 chars_decoded += len(decoder.decode(b'', final = True))
  1764.                 need_eof = 1
  1765.                 if chars_decoded < chars_to_skip:
  1766.                     raise IOError("can't reconstruct logical file position")
  1767.             return self._pack_cookie(start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
  1768.         finally:
  1769.             decoder.setstate(saved_state)
  1770.  
  1771.  
  1772.     
  1773.     def truncate(self, pos = None):
  1774.         self.flush()
  1775.         if pos is None:
  1776.             pos = self.tell()
  1777.         
  1778.         self.seek(pos)
  1779.         return self.buffer.truncate()
  1780.  
  1781.     
  1782.     def seek(self, cookie, whence = 0):
  1783.         if self.closed:
  1784.             raise ValueError('tell on closed file')
  1785.         self.closed
  1786.         if not self._seekable:
  1787.             raise IOError('underlying stream is not seekable')
  1788.         self._seekable
  1789.         if whence == 1:
  1790.             if cookie != 0:
  1791.                 raise IOError("can't do nonzero cur-relative seeks")
  1792.             cookie != 0
  1793.             whence = 0
  1794.             cookie = self.tell()
  1795.         
  1796.         if whence == 2:
  1797.             if cookie != 0:
  1798.                 raise IOError("can't do nonzero end-relative seeks")
  1799.             cookie != 0
  1800.             self.flush()
  1801.             position = self.buffer.seek(0, 2)
  1802.             self._set_decoded_chars('')
  1803.             self._snapshot = None
  1804.             if self._decoder:
  1805.                 self._decoder.reset()
  1806.             
  1807.             return position
  1808.         if whence != 0:
  1809.             raise ValueError('invalid whence (%r, should be 0, 1 or 2)' % (whence,))
  1810.         whence != 0
  1811.         if cookie < 0:
  1812.             raise ValueError('negative seek position %r' % (cookie,))
  1813.         cookie < 0
  1814.         self.flush()
  1815.         (start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip) = self._unpack_cookie(cookie)
  1816.         self.buffer.seek(start_pos)
  1817.         self._set_decoded_chars('')
  1818.         self._snapshot = None
  1819.         if self._decoder and dec_flags or chars_to_skip:
  1820.             if not self._decoder:
  1821.                 pass
  1822.             self._decoder = self._get_decoder()
  1823.             self._decoder.setstate((b'', dec_flags))
  1824.             self._snapshot = (dec_flags, b'')
  1825.         
  1826.         if chars_to_skip:
  1827.             input_chunk = self.buffer.read(bytes_to_feed)
  1828.             self._set_decoded_chars(self._decoder.decode(input_chunk, need_eof))
  1829.             self._snapshot = (dec_flags, input_chunk)
  1830.             if len(self._decoded_chars) < chars_to_skip:
  1831.                 raise IOError("can't restore logical file position")
  1832.             len(self._decoded_chars) < chars_to_skip
  1833.             self._decoded_chars_used = chars_to_skip
  1834.         
  1835.         return cookie
  1836.  
  1837.     
  1838.     def read(self, n = None):
  1839.         if n is None:
  1840.             n = -1
  1841.         
  1842.         if not self._decoder:
  1843.             pass
  1844.         decoder = self._get_decoder()
  1845.         if n < 0:
  1846.             result = self._get_decoded_chars() + decoder.decode(self.buffer.read(), final = True)
  1847.             self._set_decoded_chars('')
  1848.             self._snapshot = None
  1849.             return result
  1850.         eof = False
  1851.         result = self._get_decoded_chars(n)
  1852.         while len(result) < n and not eof:
  1853.             eof = not self._read_chunk()
  1854.             result += self._get_decoded_chars(n - len(result))
  1855.             continue
  1856.             n < 0
  1857.         return result
  1858.  
  1859.     
  1860.     def next(self):
  1861.         self._telling = False
  1862.         line = self.readline()
  1863.         if not line:
  1864.             self._snapshot = None
  1865.             self._telling = self._seekable
  1866.             raise StopIteration
  1867.         line
  1868.         return line
  1869.  
  1870.     
  1871.     def readline(self, limit = None):
  1872.         if self.closed:
  1873.             raise ValueError('read from closed file')
  1874.         self.closed
  1875.         if limit is None:
  1876.             limit = -1
  1877.         
  1878.         if not isinstance(limit, (int, long)):
  1879.             raise TypeError('limit must be an integer')
  1880.         isinstance(limit, (int, long))
  1881.         line = self._get_decoded_chars()
  1882.         start = 0
  1883.         if not self._decoder:
  1884.             pass
  1885.         decoder = self._get_decoder()
  1886.         pos = None
  1887.         endpos = None
  1888.         while True:
  1889.             if self._readtranslate:
  1890.                 pos = line.find('\n', start)
  1891.                 if pos >= 0:
  1892.                     endpos = pos + 1
  1893.                     break
  1894.                 else:
  1895.                     start = len(line)
  1896.             elif self._readuniversal:
  1897.                 nlpos = line.find('\n', start)
  1898.                 crpos = line.find('\r', start)
  1899.                 if crpos == -1:
  1900.                     if nlpos == -1:
  1901.                         start = len(line)
  1902.                     else:
  1903.                         endpos = nlpos + 1
  1904.                         break
  1905.                 elif nlpos == -1:
  1906.                     endpos = crpos + 1
  1907.                     break
  1908.                 elif nlpos < crpos:
  1909.                     endpos = nlpos + 1
  1910.                     break
  1911.                 elif nlpos == crpos + 1:
  1912.                     endpos = crpos + 2
  1913.                     break
  1914.                 else:
  1915.                     endpos = crpos + 1
  1916.                     break
  1917.             else:
  1918.                 pos = line.find(self._readnl)
  1919.                 if pos >= 0:
  1920.                     endpos = pos + len(self._readnl)
  1921.                     break
  1922.                 
  1923.             if limit >= 0 and len(line) >= limit:
  1924.                 endpos = limit
  1925.                 break
  1926.             
  1927.             more_line = ''
  1928.             while self._read_chunk():
  1929.                 if self._decoded_chars:
  1930.                     break
  1931.                     continue
  1932.             if self._decoded_chars:
  1933.                 line += self._get_decoded_chars()
  1934.                 continue
  1935.             self._set_decoded_chars('')
  1936.             self._snapshot = None
  1937.             return line
  1938.         if limit >= 0 and endpos > limit:
  1939.             endpos = limit
  1940.         
  1941.         self._rewind_decoded_chars(len(line) - endpos)
  1942.         return line[:endpos]
  1943.  
  1944.     
  1945.     def newlines(self):
  1946.         if self._decoder:
  1947.             return self._decoder.newlines
  1948.  
  1949.     newlines = property(newlines)
  1950.  
  1951.  
  1952. class StringIO(TextIOWrapper):
  1953.     """An in-memory stream for text. The initial_value argument sets the
  1954.     value of object. The other arguments are like those of TextIOWrapper's
  1955.     constructor.
  1956.     """
  1957.     
  1958.     def __init__(self, initial_value = '', encoding = 'utf-8', errors = 'strict', newline = '\n'):
  1959.         super(StringIO, self).__init__(BytesIO(), encoding = encoding, errors = errors, newline = newline)
  1960.         if newline is None:
  1961.             self._writetranslate = False
  1962.         
  1963.         if initial_value:
  1964.             if not isinstance(initial_value, unicode):
  1965.                 initial_value = unicode(initial_value)
  1966.             
  1967.             self.write(initial_value)
  1968.             self.seek(0)
  1969.         
  1970.  
  1971.     
  1972.     def getvalue(self):
  1973.         self.flush()
  1974.         return self.buffer.getvalue().decode(self._encoding, self._errors)
  1975.  
  1976.  
  1977.